var express = require('express');
var router = express.Router();
const moment = require('moment');

const shortid = require('shortid');
const checkTokenMiddleware = require('../../middlewares/checkTokenMiddleware');
const AccountsModel = require('../../models/AccountsModel');
const e = require("express");
const mongoose = require("mongoose");



//账本列表
router.get('/accounts', checkTokenMiddleware,(req, res) => {
    AccountsModel.find().sort({time: -1}).exec((error, data) => {
        if (error) {
            res.json({
                code: '1001',
                msg: '获取失败',
                data: null
            });
            return;
        }
        res.json({
            code: '0000',
            msg: "获取成功",
            data: data
        });
    });

});

//添加账本

router.post('/accounts',checkTokenMiddleware, (req, res) => {
    let id = shortid.generate();
    AccountsModel.create({
        ...req.body,
        time: moment(req.body.time).toDate()
    }, (error, data) => {
        if (error) {
            res.json({
                code: '1002',
                msg: '添加失败',
                data: null
            })
            return;
        }
        res.json({
            code: '0000',
            msg: '添加成功',
            data: data
        });
    })

})


router.delete('/accounts/:id', checkTokenMiddleware,(req, res) => {
    let id = req.params.id;
    AccountsModel.deleteOne({_id: id}).exec((error) => {
        if (error) {
            res.json({
                code: "1003",
                msg: "删除账单失败",
                data: null
            });
            return;
        }
        res.json({
            code: '0000',
            msg: '删除成功',
            data: id
        })
    });

})

router.get('/account/:id',checkTokenMiddleware,(req, res) => {
    let {id} = req.params;
    AccountsModel.findById(id, (error,data) => {
        if (error) {
            return res.json({
                code:"1004",
                msg:"获取失败~~",
                data:null
            });
        }
        res.json({
            code:"0000",
            msg:"获取成功",
            data:data
        })
    })
});


router.put('/account/:id',checkTokenMiddleware,(req, res) => {
    let {id} = req.params;
    AccountsModel.updateOne({_id:id}, req.body,(error,data) =>{
        if (error) {
            return res.json({
                code:"1005",
                msg:"修改失败",
                data:null
            });
        }
        AccountsModel.findById(id,(error,data) => {
            if (error) {
                return res.json({
                    code:"1004",
                    msg:"获取失败~~",
                    data:null
                });
            }
            res.json({
                code:"0000",
                msg:"修改成功",
                data:data
            })
        })
    })
})

module.exports = router;
